<?php
namespace app\app\model;
use app\app\util\BlockUtils;
use think\Db;
use think\Model;
use app\app\util\PointUtils;

class RoomModel extends Model{

    public $user_id;
    protected $table = "a_room";

    /**
     * 根据id获取房间
     * @param $id
     */
    public function getOne($id){
        return $this->field('*')->find($id);
    }

    /**
     * 创建房间
     */
    public function saveRoom(){
        $arr = array('master_id'=>$this->user_id,'create_time'=>time());
        $id  = Db::name('room')->insertGetId($arr);
        return $id;
    }

    /**
     * 插入对战结果
     * @param $arr
     */
    public function settleFight($arr){
        $data = array('user_id'=>$this->user_id,'room_id'=>$arr['room_id'],'result'=>$arr['result']);
        $id = Db::name('fight')->insertGetId($data);
        $room = $this->find($arr['room_id']);
        //计算时间戳
        $today = date('Y-m-d')." 23:59:59";
        $today = strtotime($today);
        $now   = time();
        $overTime = $today - $now;
        //添加客人id
        if( $room && $room['master_id'] != $this->user_id ){
            Db::name('room')->update(array('id'=>$room['id'],'guest_id'=>$this->user_id));
        }
        //加积分
        if( $arr['result'] == 1 ){
            //获胜
            $c_point = getConfig('Fight_Win');
            //加入每日战胜好友数
            $win = BlockUtils::getWin($this->user_id);
            if($win <= 2){
                //获得0.1元红包奖励
                $reward = config('Win_Reward')/100;
                Db::query('update a_users set fee = fee +'.config('Win_Reward').' where id='.$this->user_id);
            }else{
                $reward = 0;
            }
            $value = intval($win) + 1;
            BlockUtils::setWin($this->user_id,$value,$overTime);
        }elseif( $arr['result'] == 2 ){
            //输了
            $c_point = getConfig('Fight_Fail');
            $reward  = 0;
        }else{
            //平局
            $c_point = getConfig('Fight_Equal');
            $reward  = 0;
        }
        $point   = $c_point;
        PointUtils::getUserPoint($this->user_id,$point);
        Db::query('update a_users set points = points + '.$point.' where id = '.$this->user_id);
        //每天答题数目
        $answer = BlockUtils::getAnswer($this->user_id);
        $value  = intval($answer) + $arr['num'];
        BlockUtils::setAnswer($this->user_id,$value,$overTime);
        $return['point'] = $point;
        $return['reward'] = $reward;
        return $return;
    }
}